/*
 *  Copyright 2010 Alexey Frishman (alexey.frishman@gmail.com)
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may not
 *  use this file except in compliance with the License. You may obtain a copy of
 *  the License at
 *  
 *  http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 *  License for the specific language governing permissions and limitations under
 *  the License.
 * 
 */

package org.json4g;

import com.gwtent.reflection.client.ClassType;
import com.gwtent.reflection.client.Field;
import com.gwtent.reflection.client.Type;
import com.gwtent.reflection.client.TypeOracle;
import com.gwtent.reflection.client.impl.ClassTypeImpl;
import com.gwtent.reflection.client.impl.FieldImpl;

/**
 * Utility methods to simplify work with Types from GWT-ENT
 */
public class TypeUtil {

    public static boolean typesAreEqual(Type type1, Type type2) {
        return type1.getQualifiedSourceName().equals(type2.getQualifiedSourceName());
    }

    public static Type getType(Class<?> clazz) {
        return getType(TypeOracle.Instance.getClassType(clazz));
    }

    public static ClassTypeImpl getClassType(Object object) {
        return getClassType(object.getClass());
    }

    public static ClassTypeImpl getClassType(Class<?> clazz) {
        return (ClassTypeImpl) TypeOracle.Instance.getClassType(clazz);
    }

    public static Type getType(ClassType classType) {
        return (Type) classType; // implementation of ClassType is always a Type
    }

    public static boolean implementsInterface(ClassType type, Class<?> inter) {
        ClassType[] interfaces = type.getImplementedInterfaces();
        boolean result = false;
        for (ClassType i : interfaces) {
            if (typesAreEqual(getType(i), getType(inter))) {
                result = true;
                break;
            }
        }
        return result;
    }

    public static final ClassTypeImpl FAKE_CLASS_TYPE = new ClassTypeImpl(Object.class) {
        @Override
        protected void addField(FieldImpl field) {
            // nothing!
        }
    };

    public static Field fakeField(ClassTypeImpl typeOfTheField) {
        FieldImpl result = new FieldImpl(FAKE_CLASS_TYPE, "");
        result.setType(typeOfTheField);
        return result;
    }
}
